package com.neusoft.eenie.signdemo.http;


import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;

import java.net.CookieManager;
import java.util.concurrent.TimeUnit;

/**
 * Created by Eenie on 2016/3/25.
 */
public class OKHttpUtiles {

    private static OKHttpUtiles okHttp;

    private static OkHttpClient httpClient;


    public static final MediaType formReq = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");

    private static final int TIME_OUT_READ = 3;

    public static OKHttpUtiles getInstance() {
        if (okHttp == null) {
            okHttp = new OKHttpUtiles();
            httpClient = new OkHttpClient();
            httpClient.setConnectTimeout(TIME_OUT_READ, TimeUnit.SECONDS);
            httpClient.setReadTimeout(TIME_OUT_READ, TimeUnit.SECONDS);
            httpClient.setWriteTimeout(TIME_OUT_READ, TimeUnit.SECONDS);
            httpClient.setCookieHandler(new CookieManager());
        }
        return okHttp;
    }


    public void get(String url, Headers headers, Callback callback) {
        Request.Builder builder = new Request.Builder();
        builder.url(url)
                .headers(headers)
                .get();
        connect(builder.build(), callback);
    }

    public void get(String url, Callback callback) {
        Request.Builder builder = new Request.Builder();
        builder.url(url)
                .get();
        connect(builder.build(), callback);
    }


    public void post(String url, RequestBody body, Callback callback) {
        Request.Builder builder = new Request.Builder();
        builder.url(url)
                .post(body);
        connect(builder.build(), callback);
    }

    public void connect(Request request, Callback callback) {
        httpClient.newCall(request).enqueue(callback);
    }


}
